package com.lengxf.leetcode.a;

public class Leetcode_4 {

    /**
     * 给定两个大小分别为 m 和 n 的正序（从小到大）数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
     * 算法的时间复杂度应该为 O(log (m+n)) 。
     * 来源：力扣（LeetCode）
     * 链接：<a href="https://leetcode.cn/problems/median-of-two-sorted-arrays">...</a>
     */

    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 3};
        int[] nums2 = new int[]{2};
        double medianSortedArrays = findMedianSortedArrays(nums1, nums2);
        System.out.println(medianSortedArrays);
    }


    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] merge = new int[nums1.length + nums2.length];
        int mergeLength = merge.length;
        //定义两个数组的游标位置
        int cursor1 = 0;
        int cursor2 = 0;
        int cursorMerge = 0;
        while (cursorMerge < mergeLength) {
            if (cursor1 >= nums1.length) {
                merge[cursorMerge] = nums2[cursor2];
                cursor2++;
            } else if (cursor2 >= nums2.length) {
                merge[cursorMerge] = nums1[cursor1];
                cursor1++;
            } else {
                //当前游标对应数组的值
                int num1 = nums1[cursor1];
                int num2 = nums2[cursor2];
                if (num1 < num2) {
                    merge[cursorMerge] = num1;
                    cursor1++;
                } else {
                    merge[cursorMerge] = num2;
                    cursor2++;
                }
            }
            //每循环一次当前数组的游标+1
            cursorMerge++;
        }
        if (mergeLength % 2 == 0) {
            return (double) (merge[mergeLength / 2 - 1] + merge[mergeLength / 2]) / 2;
        } else {
            return merge[mergeLength / 2];
        }
    }


    /**
     * 更好的答案
     *
     * @author Lengxf
     */
    public double findMedianSortedArrays_(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int left = (m + n + 1) / 2;
        int right = (m + n + 2) / 2;
        return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0;
    }

    //i: nums1的起始位置 j: nums2的起始位置
    public int findKth(int[] nums1, int i, int[] nums2, int j, int k) {
        if (i >= nums1.length) return nums2[j + k - 1];//nums1为空数组
        if (j >= nums2.length) return nums1[i + k - 1];//nums2为空数组
        if (k == 1) {
            return Math.min(nums1[i], nums2[j]);
        }
        int midVal1 = (i + k / 2 - 1 < nums1.length) ? nums1[i + k / 2 - 1] : Integer.MAX_VALUE;
        int midVal2 = (j + k / 2 - 1 < nums2.length) ? nums2[j + k / 2 - 1] : Integer.MAX_VALUE;
        if (midVal1 < midVal2) {
            return findKth(nums1, i + k / 2, nums2, j, k - k / 2);
        } else {
            return findKth(nums1, i, nums2, j + k / 2, k - k / 2);
        }
    }


}
